package com.llpy.Service;

import com.llpy.Utils.GridFSUtils;
import com.llpy.mapper.UserMapper;
import com.mongodb.client.gridfs.GridFSBucket;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Service
public class ImgService {
    private final GridFSUtils gridFSUtils;

    @Autowired
    public ImgService(GridFSUtils gridFSUtils) {
        this.gridFSUtils = gridFSUtils;
    }

    //保存图片
    public ObjectId saveImage(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        assert fileName != null;
        return gridFSUtils.getGridFSBucket("image").uploadFromStream(fileName, inputStream);
    }

    public void deleteImg(ObjectId id){
        gridFSUtils.getGridFSBucket("image").delete(id);
    }

    public void getImage(String fileId, OutputStream outputStream) {
        gridFSUtils.getGridFSBucket("image").downloadToStream(new ObjectId(fileId), outputStream);
    }
}
